package filter;

import entity.User;
import service.UserService;
import service.impl.UserServiceImpl;
import util.Base64Utils;
import util.Constants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 过滤自动登录
 * 默认情况下过滤器只会过滤正常请求和重定向
 *
 * @version 1.0
 * @Author: xxf
 * @CreateDate: 2020/9/29 15:49
 */
@WebFilter("/login.jsp")
public class AutoFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //存放账号密码的容器
        String content = null;
        //获取客户端cookie
        Cookie[] cookies = request.getCookies();

        if (cookies != null) {
            //遍历查找autouser 的cookie
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(Constants.AUTO_NAME)) {
                    //通过cookie获取他的值
                    content = cookie.getValue();

                }
            }

            if (content != null) {
                //第一次登录对用户名和密码进行过编码
                content = Base64Utils.decode(content);
                //截取用户名密码
                String[] split = content.split(":");
                String username = split[0];
                String password = split[1];

                //调用service层重新登录
                UserService service = new UserServiceImpl();
                User user = service.login(username, password);

                //用户名密码正确后获取user对象
                if (user != null) {
                    //重新把用户信息存储导session中
                    HttpSession session = request.getSession();
                    session.setAttribute("loginUser", user);
                    //重定向
                    response.sendRedirect(request.getContextPath() + "/index.jsp");
                } else {
                    //修改过密码需要重新登录
                    chain.doFilter(req, resp);

                }

            } else {
                //从cookie中获取不到autouser的键值对，重新登录
                chain.doFilter(req, resp);
            }

        } else {

            //cookie没有存储用户信息，放行登录
            chain.doFilter(req, resp);
        }

    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

    @Override
    public void destroy() {
    }
}
